starter.controller('bookingConfirmController', function($rootScope,$state,$ionicPopup,$timeout,$scope,Page, localStore,$location,$ionicHistory,sessionStore) {
		$scope.line = $state.params.line || sessionStore.getObject('booking.line');
		$scope.order = $state.params.order  || sessionStore.getObject('booking.order');
		
		if(!$scope.order || !$scope.line || !$scope.line.stops 
				|| !$scope.order.plan || !$scope.order.plan.planId
				|| !$scope.order.rideDates || $scope.order.rideDates.length == 0
				|| !$scope.order.passengers || $scope.order.passengers.length == 0){
			return false;
		}
		
		$scope.order.orderAmount = $scope.line.price * $scope.order.rideDates.length * $scope.order.passengers.length;
		$scope.order.discountAmount = $scope.order.orderAmount;
		$scope.order.discountId = null;
		
		$scope.order.dates = '';
		$($scope.order.rideDates).each(function(idx,date){
			$scope.order.dates += (idx == 0 ? '' : ',') + date;
		});
		
		var discountParams = {
			lineId : $scope.line.lineId,
			planId : $scope.order.plan.planId,
			dates : $scope.order.dates,
			passengerCount :  $scope.order.passengers.length
		};
		$scope.orderDiscounts = [];
		Page.ajaxPost('app/order/getDiscount.do',discountParams,function(resp){
			$scope.orderDiscounts = resp.data;
			if($scope.orderDiscounts && $scope.orderDiscounts.length > 0){
				$scope.order.discountId = $scope.orderDiscounts[0].discountId;
				$scope.order.discountAmount =  $scope.orderDiscounts[0].discountAmount;
			} else {
				$scope.order.discountAmount = $scope.order.orderAmount;
			}
		},function(resp){
			$scope.order.discountAmount = $scope.order.orderAmount;
		});

		
	    $scope.$watch('order.discountId', function (newValue, oldValue) {
	        if (typeof newValue != 'undefined' && newValue != '') {
	            $($scope.orderDiscounts).each(function(idx,orderDiscount){
					if(newValue == orderDiscount.discountId){
						$scope.order.discountAmount =  orderDiscount.discountAmount;
					}
				});
	        }
	    });
		
		$scope.submitOrder = function(){
			var order = {
				    lineId: $scope.line.lineId, // 线路id
				    planId: $scope.order.plan.planId, // 方案id
				    discountId: $scope.order.discountId, // 折扣id
				    passengers: $scope.order.passengers,// 乘车人信息
				    dates: $scope.order.dates // 乘坐日期，以逗号隔开
			};
			Page.ajaxPostQuiet('app/order/create.do',order ,function(resp){
				Page.confirm("订单已提交，现在去付款吗？",function(){
					$state.go('order_pay', {orderId : resp.data});
				},function(){
					$state.go('orders');
				});
			});
		};
});